<?php
namespace addons\jieziaddress\model;

use think\Model;

class JieziaddressUserAddress extends Model {
    //地址列表
    public function addressList($uid){
        $address = $this->alias('a')
            ->field('a.id, a.name, a.phone, a.address, a.is_default, a1.name as province_name, a2.name as city_name, a3.name as district_name')
            ->join('jieziarea a1', 'a.province_id = a1.id', 'left')
            ->join('jieziarea a2', 'a.city_id = a2.id', 'left')
            ->join('jieziarea a3', 'a.district_id = a3.id', 'left')
            ->where('user_id', $uid)
            ->where('is_del', 0)
            ->order('a.is_default desc, id desc')
            ->select();//收货地址信息
        foreach ($address as $v=>$l){
            $info[$v]['cont'] = $l['province_name'].$l['city_name'].$l['district_name'].$l['address'];//收货地址
            $info[$v]['phone'] = $l['phone'];
            $info[$v]['name'] = $l['name'];
            $info[$v]['id'] = $l['id'];
            if ($l['is_default']){
                $info[$v]['is_default'] = 1;
            }else{
                $info[$v]['is_default'] = 0;
            }
        }

        if (!empty($info)){
            return $info;
        }else{
            return [];
        }
    }

    /**
     * 获取详细
     * @param $user_id
     * @param null $id
     * @param int $default 是否默认
     */
    public function info($user_id, $id = null, $default = 0){
        $table = $this->alias('a')
            ->field('a.id, a.name, a.phone, a.province_id, a.city_id, a.district_id, a.address, a.location, a.is_default, a.lat, a.lng');
        if($default){
            $table->where('a.user_id', $user_id)->where('is_default', 1);
        }else {
            $table->where('a.id', $id)->where('a.user_id', $user_id);
        }
        $thing = $table
            ->where('is_del', 0)->find();
        if(empty($thing)){
            $thing = [];
        }else{
            if(empty($thing['location'])){
                $thing['province_name'] = $thing['city_name'] = $thing['district_name'] = '';
            }else{
                $arr = explode('|', $thing['location']);
                $thing['province_name'] = $arr[0];
                $thing['city_name'] = $arr[1];
                $thing['district_name'] = $arr[2];
            }
            unset($thing['location']);
            $thing['pid'] = $thing['province_id'];
            $thing['cid'] = $thing['city_id'];
            $thing['aid'] = $thing['district_id'];
            $thing['detail'] = $thing['address'];
            $thing['area'] = $thing['province_name'] . ' ' . $thing['city_name'] . ' ' . $thing['district_name'];
            $thing['cont'] = $thing['province_name'] . ' ' . $thing['city_name'] . ' ' . $thing['district_name'] . ' ' . $thing['address'];
        }
        return $thing;
    }
}